package com.garlicts.framework.rpc;

import com.garlicts.framework.annotation.RpcConsume;
import com.garlicts.framework.ioc.BeanContainerComponent;
import com.garlicts.framework.ioc.IocInit;
import com.garlicts.framework.util.ArrayUtil;

import java.lang.reflect.Field;
import java.util.Map;

public class RpcComponent implements IocInit {

    static {

    }

    @Override
    public void init() {

        Map<Class<?>, Object> beanMap = BeanContainerComponent.getBeanMap();
        for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
            // 获取 Bean 类与 Bean 实例
            Class<?> beanClass = beanEntry.getKey();
            Object beanInstance = beanEntry.getValue();
            // 获取 Bean 类中所有的字段（不包括父类中的方法）
            Field[] beanFields = beanClass.getDeclaredFields();
            if (ArrayUtil.isNotEmpty(beanFields)) {
                // 遍历所有的 Bean 字段
                for (Field beanField : beanFields) {
                    // 判断当前 Bean 字段是否带有 Autowired 注解
                    if (beanField.isAnnotationPresent(RpcConsume.class)) {

                        RpcConsume rpcConsume = beanField.getAnnotation(RpcConsume.class);
                        // 获取 Bean 字段对应的接口
                        Class<?> interfaceClass = beanField.getType();
                        beanField.setAccessible(true);
                        try {
                            beanField.set(beanInstance, RpcClientProxy.create(interfaceClass, rpcConsume.rpcServiceName()));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }finally {
                            beanField.setAccessible(false);
                        }

                    }

                }
            }
        }

    }

}
